<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";

if ($login['username'] == "")
{
  header ("location: ./");
  exit;
}

$connection = db_open ();

/* Create the XML feed */
if (isset ($_POST['pid']))
{
  $path = isset ($_POST['path']) ? $_POST['path'] : "";
  $path = str_replace (" ", "_", $_POST['path']);
  while (substr ($path, 0, 1) == "/")
    $path = substr ($path, 1);
    
  $title = htmlentities (trim ($_POST['title']), ENT_COMPAT, "UTF-8", false);
  $title = htmlentities ($title, ENT_COMPAT, "UTF-8", true);
  
  $xmlfeed = "<page><title>$title</title><fields>";
  
  $tbl_pages = db_maketablename ($table_pages);
  $tbl_templates = db_maketablename ($table_templates);
  $result = mysql_query ("SELECT $tbl_templates.fields FROM $tbl_pages LEFT JOIN $tbl_templates ON $tbl_templates.id=$tbl_pages.template WHERE $tbl_pages.id='{$_POST['pid']}'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      /* Prepare the XML parser and parse the data */
      $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".$row['fields'];     
      $xmlres = xml_parser_create ("utf-8");
      xml_parse_into_struct ($xmlres, $xmldata, $values);
      xml_parser_free ($xmlres);
      
      /* Walk through the tags */
      $i = 0;
      while ($values[$i])
        {
          if ($values[$i]['level'] == 2 && strcasecmp ($values[$i]['tag'], "field") == 0 && isset ($values[$i]['attributes']['NAME']))
            {
              $name = $values[$i]['attributes']['NAME'];
              $value = htmlentities (trim ($_POST[$name]), ENT_COMPAT, "UTF-8", false);
              $value = str_replace ("&copy;", "&amp;copy;", $value);
              $xmlfeed .= "<$name>$value</$name>";
            }
          $i++;
        }
    }
  mysql_free_result ($result);

  $xmlfeed .= "</fields></page>";
  
  /* Now update the page in the database */
  if ($path != "")
    mysql_query ("UPDATE ".db_maketablename ($table_pages)." SET path='".mysql_real_escape_string ($path)."', template='{$_POST['template']}', xmlfeed='".mysql_real_escape_string ($xmlfeed)."' WHERE id='{$_POST['pid']}'");
  else
    mysql_query ("UPDATE ".db_maketablename ($table_pages)." SET template='{$_POST['template']}', xmlfeed='".mysql_real_escape_string ($xmlfeed)."' WHERE id='{$_POST['pid']}'");
}

db_close ($connection);
header ("location:$app_adminpath/?p=site&pid={$_POST['pid']}");
exit;
?>
